﻿/*
Copyright (c) 2009, Luke Berndt
All rights reserved.
 
 * More Information: http://www.tagflo.com

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions 
  and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of RoboTastic Software nor the names of its contributors may be used to endorse or 
  promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED 
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Threading;
using System.IO;
using FlickrNet;
using System.Windows.Media;

namespace TagFlo
{
public enum ExportType          
{
       flickr
    }

    public class ExportItem
    {
        ExportType exportType;
        Photo photo;
        int maxEdge;
        //BitmapImage image;
        
        public ExportItem(ExportType et, Photo p, int edge)
        {
            exportType = et;
            photo = p;
            maxEdge = edge;
        }

      /*  public StatusItem(StatusUpdateType ut, string t, BitmapImage i)
        {
            updateType = ut;
            text = t;
            image = i;
        }*/


        public int MaxEdge
        {
            get { return maxEdge; }
        }
        public ExportType Export
        {
            get { return exportType; }

        }
      
        public Photo ExportPhoto
        {
            get { return photo; }
        }
    }



    public class ExportWorker
    {
        MainWindow parent;
        Configuration config;
        Flickr flickr;
        private string ApiKey = "c2c7061315df6b1da603bd3ab2d164e4";
        private string SharedSecret = "139d4ebe62dee130";

        private static readonly object _lockStack = new object();

        private static AutoResetEvent _updateExportEvent = new AutoResetEvent(false);

        private static readonly Stack<ExportItem> _exportStack = new Stack<ExportItem>();

        private void Flickr_OnUploadProgress(object sender, UploadProgressEventArgs e)
        {
            Console.WriteLine("Upload progress: {0} ", e.Bytes);
        }

        private string ResizePhoto(string path, int maxEdge)
        {
        
           Uri source = new Uri(path);

            byte[] buffer = File.ReadAllBytes(path);
            MemoryStream mem = new MemoryStream(buffer);

           
            BitmapFrame image = BitmapFrame.Create(mem);
            BitmapImage thumbnail = new BitmapImage();
            int width = (int)image.Width;
            int height = (int)image.Height;
            FileInfo file = new FileInfo(path);
            Uri uri = new Uri(System.Reflection.Assembly.GetEntryAssembly().GetName().CodeBase);
            FileInfo f = new FileInfo(uri.LocalPath);
            string tempFile =  f.DirectoryName + "\\" + file.Name;
              
            //String tempFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + file.Name;
              

            try
            {
                thumbnail.BeginInit();

             

                if (image.Width > image.Height)
                {
                    thumbnail.DecodePixelWidth = maxEdge;
                }
                else
                {
                    thumbnail.DecodePixelHeight = maxEdge;
                }
                mem.Seek(0, SeekOrigin.Begin);

                thumbnail.StreamSource = mem;

                thumbnail.CreateOptions = BitmapCreateOptions.None;

                thumbnail.CacheOption = BitmapCacheOption.Default;

                RenderOptions.SetBitmapScalingMode(thumbnail, BitmapScalingMode.NearestNeighbor);

                thumbnail.EndInit();
                thumbnail.Freeze();

                using (FileStream stream = new FileStream(tempFile, FileMode.Create))
                {
                    BitmapEncoder encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(thumbnail as BitmapSource));
                    encoder.Save(stream);
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }


            return tempFile;
        }


        private void FlickrExport(Photo p, int maxEdge)
        {
            
            string filePath = p.FullFilename;
           string tempFilePath = ResizePhoto(filePath, maxEdge);
           FileInfo tempFile = new FileInfo(tempFilePath);
            string title = p.Title;
            string descripton = p.Subject;
            string tags = "";
            foreach (Tag t in p.Tags)
            {
                tags = tags + t.TagName + ", ";
            }
            try
            {
                
                Flickr.CacheDisabled = true;
                string photoId = flickr.UploadPicture(tempFilePath, title, descripton, tags,false,false,false);
                parent.AddExportUpdate(p.Filename, p.Thumbnail);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                parent.AddExportErrorUpdate("Error Exprorting: " + p.Filename + "\n - " + s);
            }
            tempFile.Delete();
            

        }
        public void AddExportItem(ExportItem item)
        {
            lock (_lockStack)
            {
                _exportStack.Push(item);
            }
            _updateExportEvent.Set();
        }

        public void AddFlickrExport(Photo p, int maxEdge)
        {
            ExportItem item = new ExportItem(ExportType.flickr, p, maxEdge);
            AddExportItem(item);

        }

        public void UpdateExportThread()
        {
            ExportItem item = null;
            bool moreWork = false;
            do
            {
                _updateExportEvent.WaitOne();
                do
                {
                    try
                    {

                        lock (_lockStack)
                        {
                            if (_exportStack.Count > 0)
                            {
                                item = _exportStack.Pop();
                            }
                        }

                        if (item != null)
                        {
                            switch (item.Export)
                            {
                                case ExportType.flickr:
                                    FlickrExport(item.ExportPhoto, item.MaxEdge);
                                    break;
                            }
                        }

                        Thread.Sleep(10);
                        lock (_lockStack)
                        {
                            if (_exportStack.Count == 0)
                            {
                                moreWork = false;
                            }
                            else
                            {
                                moreWork = true;
                            }
                        }


                    }
                    catch
                    {
                    }
                } while (moreWork);
                Thread.Sleep(1000);
            } while (true);
        }
         public ExportWorker(MainWindow p,Configuration c)
        {
            config = c;
            parent = p;
            flickr = new Flickr(ApiKey, SharedSecret, config.FlickerToken);
            flickr.OnUploadProgress += new Flickr.UploadProgressHandler(Flickr_OnUploadProgress);

          

        }

        public void UpdateExport()
        {
            flickr = new Flickr(ApiKey, SharedSecret, config.FlickerToken);
            flickr.OnUploadProgress += new Flickr.UploadProgressHandler(Flickr_OnUploadProgress);


        }
    }
}
